package com.crm.interceptor;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.crm.entity.User;

import org.springframework.web.method.HandlerMethod;



public class LoginHandler implements HandlerInterceptor{
	 @Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
	        Object handler) throws IOException {
	 
	        
	        if (!(handler instanceof HandlerMethod)) {
				return true; 
			}
	        String token = request.getHeader("token");
	 
	        // 有token表示用户已登录（生产环境应该校验token合法性）
	        if (token!=null&&token!="") {
	        	try {
					User user=AuthenticationInterceptor.unsign(token, User.class);
					if (user!=null) {
						return true;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
	            
	        } 
	        response.setCharacterEncoding("UTF-8");
	        response.setContentType("application/json;charset=utf-8");
	        response.getWriter().append("认证失败！请检查登录信息");
	        return false;
	       
	    }
	 
	    /**
	     * 通过response返回错误信息给前端
	     *
	     * @param request 请求
	     * @param response 响应
	     * @param content 响应内容
	     */
	    private void write(HttpServletRequest request, HttpServletResponse response, String content)
	        throws IOException {
	 
	        String origin = request.getHeader("Origin");
	        response.setHeader("Access-Control-Allow-Origin", origin);
	        response.setCharacterEncoding("UTF-8");
	        response.setContentType("application/json; charset=utf-8");
	        response.getWriter().write(content);
	    }

}
